package cn.haut.online_read.service;

import cn.haut.online_read.enrity.BookInfo;
import cn.haut.online_read.mapper.BookshelfMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xing
 * @date 2021-05-14 18:57
 */
@Service("bookshelfService")
@Slf4j
public class BookshelfService {

    private BookshelfMapper bookshelfMapper;

    @Autowired
    public void setBookshelfMapper(BookshelfMapper bookshelfMapper){
        this.bookshelfMapper = bookshelfMapper;
    }

    /**
     * 添加到书架
     *
     * @param username
     * @param bookInfo
     * @return
     */
    public boolean addBookshelfByUserId(String username, BookInfo bookInfo) {
        // 查找书籍信息
        // 与表 长度不对应，报错
//        BookInfo getBook = bookshelfMapper.getBookInfoById(bookInfo.getId());
        Integer infoCount = bookshelfMapper.getInfoCountById(bookInfo.getId());
        // 不存在，添加
        if(infoCount == null || infoCount == 0) {
            Integer add = bookshelfMapper.addBookInfo(bookInfo);
            if(add == null) {
                // 添加失败，未知错误，返回 false
                return false;
            }
            // 添加书籍信息成功
        }
        // 关联
        Integer add = bookshelfMapper.addShelf(username, bookInfo.getId());
        if(add == null) {
            // 关联失败，未知错误，返回 false
            return false;
        }
        // 添加书架成功
        return true;
    }

    public boolean isExist(String username, String bookId) {
        Integer count = bookshelfMapper.getCountByAll(username, bookId);
        return count != null && count != 0;
    }

    /**
     * 获取书架里书籍
     * TODO 这里返回的 Map 因为与数据库数量不对应，但是暂时又不需要其他信息，
     * BookInfo 开始主要是用来放爬取的书籍信息的
     *
     * @param username
     * @return
     */
    public List<BookInfo> getBooks(String username) {
        List<Map<String, String>> list = bookshelfMapper.getBooks(username);
        if(list.isEmpty()) {
            return new ArrayList<>();
        }
        List<BookInfo> bookInfoList = new ArrayList<>();
        for (Map<String, String> stringStringMap : list) {
            bookInfoList.add(new BookInfo(
                    stringStringMap.get("id"),
                    stringStringMap.get("name"),
                    null,
                    null,
                    stringStringMap.get("imgUrl"),
                    null,
                    null
                    ));
        }
        return bookInfoList;
    }

    /**
     * 书籍从书架删除
     *
     * @param username
     * @param bookId
     * @return
     */
    public boolean removeBook(String username, String bookId) {
        Boolean remove = bookshelfMapper.removeBook(username, bookId);
        return remove != null && remove;
    }
}
